package fsoperation;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import mudus.GlobalSettings;
import mudus.UserInfo;

public class FileUtil {            
            
    //membuat file kosong di repo user(pathnya relative pada folder user di repo)
    public static boolean makeFile(UserInfo userInfo, String path, String filename) throws IOException {
        String fullPath = GlobalSettings.REPO_PATH + "/" + userInfo.getUsername() + "/" + path;                
        File f = new File(fullPath, filename);
        File parent = f.getParentFile();
        if(!parent.exists()) {
            parent.mkdirs();
        }
        if(!f.exists()) {
            return f.createNewFile();
        }        
        return false;
    }
    
    public static void sendFile(UserInfo userInfo, String filepath) {
        //split file menjadi k bagian, dengan tiap potong 
    }
    
    public static File getFile(UserInfo userInfo, String filepath, String filename) throws FileNotFoundException {
        String fullPath = GlobalSettings.REPO_PATH + "/" + userInfo.getUsername() + "/" + filepath;                
        File f = new File(fullPath, filename);        
        return f;
    }        
    
    public static void appendFile(UserInfo userInfo, String path, String filename, byte[] data) throws IOException {
        String fullPath = GlobalSettings.REPO_PATH + "/" + userInfo.getUsername() + "/" + path;
        File file = new File(fullPath, filename);
        
        FileOutputStream fos = new FileOutputStream(file,true);        
        BufferedOutputStream bos = new BufferedOutputStream(fos);        
        bos.write(data);
        bos.flush();
        bos.close();
    }
    
    public static void main(String[] args) {
        try {
            UserInfo userInfo = new UserInfo(1, "hilmanbeyri");
            System.out.println("hasil make file : " + makeFile(userInfo, "", "empty.file"));
            String test1 = "Hilman Beyri";
            String test2 = "Siregar";
            System.out.println("test append file (tidak ada log)");
            appendFile(userInfo, "", "empty.file",  test1.getBytes());
            appendFile(userInfo, "", "empty.file",  test2.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
